import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/a_yyt/models/medical_elder_entity.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/model/customer_info_model.dart';
import 'package:ls_work/model/health/health_model.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/resources.dart';
import 'package:ls_work/ui/select_old_page.dart';
import 'package:ls_work/widgets/common_widget.dart';

import '../../a_elder/models/elder_entity.dart';
import '../../widgets/input_number_view.dart';

class NewHealthSignViewModel extends BaseViewModel {
  NewHealthSignViewModel(BuildContext context,{ElderInfo? info}) : super(context){
    if(info!=null){
      elder = MedicalElderInfo.fromJson(info.toJson());
    }
  }

  MedicalElderInfo? elder;
  var customerModel = CustomerInfoModel();
  var healthModel = HealthModel();

  var inEditMode = true;

  var hasChanged = false;

  var remark = "";

  // var listItem = [
  //   ///体温
  //   HealthSignRequestData(
  //       titleName: "体温",
  //       type: HealthSignType.CHOOSE,
  //       tagList: [
  //         PickerDataWithIdModel(pickName: '腋温', pickId: 'axillaryTemperature'),
  //         PickerDataWithIdModel(pickName: '肛温', pickId: 'analTemperature'),
  //         PickerDataWithIdModel(
  //             pickName: '电子', pickId: 'electronicTemperature'),
  //         PickerDataWithIdModel(pickName: '体温', pickId: 'temperature'),
  //       ],
  //       unit: '℃'),
  //
  //   ///进量
  //   HealthSignRequestData(
  //       titleName: '进量',
  //       unit: 'ml',
  //       type: HealthSignType.CHOOSE,
  //       tagList: [
  //         PickerDataWithIdModel(pickName: '进餐', pickId: 'waterProtein'),
  //         PickerDataWithIdModel(pickName: '补水', pickId: 'milkProtein'),
  //         PickerDataWithIdModel(pickName: '输液', pickId: 'soupProtein'),
  //       ]),
  //
  //   HealthSignRequestData(titleName: '血氧饱和度', unit: "%", tagName: "oxygen"),
  //   HealthSignRequestData(titleName: '收缩压', unit: "mmHg", tagName: "high"),
  //   HealthSignRequestData(titleName: '舒张压', unit: "mmHg", tagName: "low"),
  //   HealthSignRequestData(titleName: '脉搏', unit: "bpm", tagName: "pulseRate"),
  //   HealthSignRequestData(titleName: '心率', unit: "bpm", tagName: "heart"),
  //   HealthSignRequestData(titleName: '体重', unit: "kg", tagName: "weight"),
  //   HealthSignRequestData(titleName: '身高', unit: "cm", tagName: "height"),
  //
  //   HealthSignRequestData(
  //       titleName: '血糖-早餐前',
  //       unit: "mmol/L",
  //       tagName: "bloodSugarBeforeBreakfast"),
  //   HealthSignRequestData(
  //       titleName: '血糖-早餐后',
  //       unit: "mmol/L",
  //       tagName: "bloodSugarLastBreakfast"),
  //
  //   HealthSignRequestData(
  //       titleName: '血糖-午餐前', unit: "mmol/L", tagName: "bloodSugarBeforeLunch"),
  //   HealthSignRequestData(
  //       titleName: '血糖-午餐后', unit: "mmol/L", tagName: "bloodSugarLastLunch"),
  //
  //   HealthSignRequestData(
  //       titleName: '血糖-晚餐前', unit: "mmol/L", tagName: "bloodSugarBeforeDinner"),
  //   HealthSignRequestData(
  //       titleName: '血糖-晚餐后', unit: "mmol/L", tagName: "bloodSugarLastDinner"),
  //
  //   HealthSignRequestData(
  //       titleName: '血糖-睡前', unit: "mmol/L", tagName: "bloodSugarBeforeSleep"),
  //   HealthSignRequestData(
  //       titleName: '血糖-其他', unit: "mmol/L", tagName: "bloodSugarLastOther"),
  // ];

  var listItem = [
    HealthSignRequestData(
        titleName: '身高',
        unit: "cm",
        tagName: "height",
        icon: HealthIcons.icon_height),
    HealthSignRequestData(
        titleName: '体重',
        unit: "kg",
        tagName: "weight",
        icon: HealthIcons.icon_weight),
    HealthSignRequestData(
        titleName: '舒张压',
        unit: "mmHg",
        tagName: "low",
        icon: HealthIcons.icon_blood_pressure),
    HealthSignRequestData(
        titleName: '收缩压',
        unit: "mmHg",
        tagName: "high",
        icon: HealthIcons.icon_blood_pressure),
    HealthSignRequestData(
        titleName: '血氧',
        unit: "%",
        tagName: "oxygen",
        icon: HealthIcons.icon_blood_oxygen),
    HealthSignRequestData(
        titleName: '脉率',
        unit: "bpm",
        tagName: "pulseRate",
        icon: HealthIcons.icon_pulse_rate),
    HealthSignRequestData(
        titleName: '心率',
        unit: "bpm",
        tagName: "heart",
        icon: HealthIcons.icon_heart_rate),
    HealthSignRequestData(
        titleName: '体温',
        unit: "℃",
        tagName: "temperature",
        icon: HealthIcons.icon_temp),
    HealthSignRequestData(
        titleName: '大便',
        unit: "次",
        tagName: "bowelsNum",
        icon: HealthIcons.icon_stool),
    HealthSignRequestData(
        titleName: '呼吸',
        unit: "次",
        tagName: "breathe",
        icon: HealthIcons.icon_breath),

    ///体温
    // HealthSignRequestData(
    //     titleName: "体温",
    //     type: HealthSignType.CHOOSE,
    //     tagList: [
    //       PickerDataWithIdModel(pickName: '腋温', pickId: 'axillaryTemperature'),
    //       PickerDataWithIdModel(pickName: '肛温', pickId: 'analTemperature'),
    //       PickerDataWithIdModel(
    //           pickName: '电子', pickId: 'electronicTemperature'),
    //       PickerDataWithIdModel(pickName: '体温', pickId: 'temperature'),
    //     ],
    //     unit: '℃'),

    ///进量
    // HealthSignRequestData(
    //     titleName: '进量',
    //     unit: 'ml',
    //     type: HealthSignType.CHOOSE,
    //     tagList: [
    //       PickerDataWithIdModel(pickName: '进餐', pickId: 'waterProtein'),
    //       PickerDataWithIdModel(pickName: '补水', pickId: 'milkProtein'),
    //       PickerDataWithIdModel(pickName: '输液', pickId: 'soupProtein'),
    //     ]),
    HealthSignRequestData(
        titleName: '血糖-早餐前',
        unit: "mmol/L",
        tagName: "bloodSugarBeforeBreakfast",
        icon: HealthIcons.icon_blood_sugar),
    HealthSignRequestData(
        titleName: '血糖-早餐后',
        unit: "mmol/L",
        tagName: "bloodSugarLastBreakfast",
        icon: HealthIcons.icon_blood_sugar),

    HealthSignRequestData(
        titleName: '血糖-午餐前',
        unit: "mmol/L",
        tagName: "bloodSugarBeforeLunch",
        icon: HealthIcons.icon_blood_sugar),
    HealthSignRequestData(
        titleName: '血糖-午餐后',
        unit: "mmol/L",
        tagName: "bloodSugarLastLunch",
        icon: HealthIcons.icon_blood_sugar),

    HealthSignRequestData(
        titleName: '血糖-晚餐前',
        unit: "mmol/L",
        tagName: "bloodSugarBeforeDinner",
        icon: HealthIcons.icon_blood_sugar),
    HealthSignRequestData(
        titleName: '血糖-晚餐后',
        unit: "mmol/L",
        tagName: "bloodSugarLastDinner",
        icon: HealthIcons.icon_blood_sugar),

    HealthSignRequestData(
        titleName: '血糖-睡前',
        unit: "mmol/L",
        tagName: "bloodSugarBeforeSleep",
        icon: HealthIcons.icon_blood_sugar),
    HealthSignRequestData(
        titleName: '血糖-其他',
        unit: "mmol/L",
        tagName: "bloodSugarLastOther",
        icon: HealthIcons.icon_blood_sugar),
  ];

  Widget itemWidget(HealthSignRequestData item) {
    if (item.type == HealthSignType.INPUT) {
      return TitleContentWidget(
          title: '${item.titleName}(${item.unit})',
          titleWeight: 3,
          contentWeight: 3,
          child: CommonText(
            item.value ?? "",
            hintText: '请输入',
          )
          // child: NoBorderInput(
          //     inEditModel: inEditMode,
          //     hintText: '请输入',
          //     maxLines: 1,
          //     text: item.value ?? "",
          //     focusNode: item.node,
          //     textInputAction: TextInputAction.next,
          //     keyboardType: CommonInputType.numberAndDecimal,
          //     onChanged: (str) {
          //       item.value = str;
          //     })
          ).onTap(() async {
        // String? str =
        await showHealthNumberInput(context,
            healthItems: listItem,
            position: listItem.indexOf(item), onChangedListener: (value) {
          notifyListeners();
        });
        // if (str != null) {
        //   item.value = str;
        //   notifyListeners();
        // }
      });
    } else {
      return Column(
        children: [
          TitleValueWidget(
                  title: '${item.titleName}',
                  value: item.selectTag?.name ?? "",
                  titleWeight: 3,
                  contentWeight: 3,
                  arrow: Icon(Icons.keyboard_arrow_right))
              .onTap(() {
            DataPickerView(context, item.tagList,
                currentFirstData: item.selectTag,
                onSubmitListener: (p1, p2, p3) {
              item.selectTag = item.tagList[p1];
              item.tagName = item.selectTag?.pickId ?? "";
              notifyListeners();
            }).show();
          }),
          Gaps.line,
          TitleContentWidget(
              title:
                  '${item.titleName}(${item.selectTag?.pickName ?? ""}${item.unit})',
              titleWeight: 3,
              contentWeight: 3,
              child: NoBorderInput(
                  inEditModel: inEditMode,
                  focusNode: item.node,
                  hintText: '请输入',
                  maxLines: 1,
                  text: item.value ?? "",
                  textInputAction: TextInputAction.next,
                  keyboardType: CommonInputType.numberAndDecimal,
                  onSubmitted: (str) {
                    item.node?.unfocus();
                    var index = listItem.indexOf(item);
                    if (index != listItem.length - 1) {
                      listItem[index + 1].node?.requestFocus();
                    }
                  },
                  onChanged: (str) {
                    item.value = str;
                  }))
        ],
      );
    }
  }

  Future<void> onItemClick(HealthSignRequestData item) async {
    await showHealthNumberInput(context,
    healthItems: listItem,
    position: listItem.indexOf(item), onChangedListener: (value) {
      notifyListeners();
    });
  }

  void chooseElder() {
    Go().push(SelectOldPage((old) {
      Go().pop();
      elder = old;
      notifyListeners();
    },useLastFilter: true,));
  }

  Future<void> submitHealth() async {
    if (elder == null) {
      showToast("请选择长者");
      return;
    }

    var map = {
      "customerId": elder?.id,
      "collectionTime": DateTime.now()
          .toDateStr([yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ':', ss]),
      "sourceId": 3,
      "remark": remark,
    };
    for (var item in listItem) {
      if (!item.tagName.isNullOrEmpty() && !item.value.isNullOrEmpty()) {
        map[item.tagName] = item.value;
      }
    }

    // return;
    showLoadingDialog(msg: '提交中...');
    try {
      await healthModel.submitHealthSign(map);
      hideDialog();
      reset();
    } catch (e) {
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }

  void reset() {
    inEditMode = false;
    notifyListeners();
    elder = null;
    remark = "";
    for (var item in listItem) {
      item.selectTag = null;
      item.value = "";
    }
    Future.delayed(Duration(milliseconds: 100), () {
      inEditMode = true;
      notifyListeners();
    });
  }

  void backClick() {
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            content: CommonText("确定要退出当前页面吗?", textAlign: TextAlign.center),
            actions: [
              TextButton(
                  onPressed: () {
                    finish();
                  },
                  child: CommonText('取消', textColor: Colors.black)),
              TextButton(
                  onPressed: () {
                    finish();
                    finish();
                  },
                  child: CommonText('确定', textColor: Colors.blue)),
            ],
          );
        });
  }

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if(event.msgCode==MessageConfig.NFC_READ_IC_CARD){
      var cardNumber = event.obj as String;
      getCustomerByCard(cardNumber);
    }

  }

  Future<void> getCustomerByCard(String cardNumber) async {
   showLoadingDialog();
   try{
     var old =  await customerModel.getCardAccount(physicalCardNo: cardNumber);
     var info = await customerModel.getElderInfo(old!.data!.human!.id.toString());
     hideDialog();
     elder = MedicalElderInfo.fromJson(info.toJson());
     notifyListeners();
   }catch(e){
     hideDialog();
     showToast(e.toNetError());
   }
  }
}

class HealthSignRequestData {
  String titleName;
  HealthSignType type;
  String tagName;
  String value;
  PickerDataWithIdModel? selectTag;
  List<PickerDataWithIdModel> tagList;
  String unit;
  FocusNode? node;
  IconData? icon;

  HealthSignRequestData(
      {required this.titleName,
      this.type = HealthSignType.INPUT,
      this.tagName = "",
      this.value = "",
      this.selectTag,
      this.tagList = const [],
      this.unit = "",
      this.node,
      this.icon}) {
    this.node ??= FocusNode();
  }
}

enum HealthSignType { INPUT, CHOOSE }
